<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocketTest</title>
    <script>
        url='ws://localhost:8081/ws'
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket
        }
        if (window.WebSocket) {
            socket = new WebSocket(url)
            socket.onopen = function(event) {
                addMsg('连接成功')
                console.log(event)
            }
            socket.onclose = function(event) {
                addMsg('连接被关闭')
            }
            socket.onmessage = function(event) {
                addMsg("【服务器】："+event.data)
            }
        } else {
            alert('你的浏览器不支持 WebSocket！')
        }

        function addMsg(msg) {
            let content=document.getElementById('content')
            content.innerHTML=content.innerHTML+msg+"<br>"
        }
        function send() {
            let msg=document.getElementById('input').value
            if(msg){
                if (!window.WebSocket) {
                    return
                }
                if (socket.readyState == WebSocket.OPEN) {
                    socket.send(msg)
                    addMsg("【客户端】："+msg)
                    document.getElementById('input').value=''
                } else {
                    alert('连接没有开启.')
                }
            }else{
                alert('不允许空消息')
            }
        }
    </script>
</head>
<body>
<div  id="content" style="width: 800px;height: 600px;">

</div>
<div style="width: 800px;height: 120px">
    <textarea  id="input" placeholder="请输入短信内容" style="width: 100%;height: 80px"></textarea>
    <button onclick="send()">发送</button>
</div>
</body>
</html>